package org.sjs.dreamfly.biz.movie

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.common.eventbus.Subscribe
import kotlinx.coroutines.launch
import org.sjs.dreamfly.R
import org.sjs.dreamfly.app.MovieListLoadedEvent
import org.sjs.dreamfly.app.defaultEventBus
import org.sjs.dreamfly.browser.WebViewFragment
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.data.Config

abstract class MovieListFragment : WebViewFragment() {

    protected lateinit var viewModel: MovieListViewModel

    protected lateinit var recyclerView: RecyclerView
    protected open var channelType: String = Config.defaultChannelType4XiGua

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this)[MovieListViewModel::class.java]
        viewModel.init(channelType)
        defaultEventBus.register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        defaultEventBus.unregister(this)
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe()
    private fun onEventMovieListLoaded(event: MovieListLoadedEvent) {
        if (event.location?.href?.contains(channelType) == true) {
            LogUtil.d("channel:${channelType}, href:${event.location?.href}, movies:${event.movieList}")
            val index = viewModel.getMovieList().size
            mainScope.launch {
                viewModel.onMovieListLoaded(event.movieList)
                val count = viewModel.getMovieList().size - index
                if (count > 0) {
                    recyclerView.adapter?.notifyItemRangeInserted(index, count)
                }
            }
        }
    }

    override fun onBindViews() {
        super.onBindViews()
        val view = requireView()
        recyclerView = view.findViewById(R.id.recycler_view)
    }

    override fun requireCustomLayoutId(): Int {
        return R.layout.fragment_movie
    }

    override fun onInitViews() {
        super.onInitViews()
        hideTitleBar()
        recyclerView.adapter = object : RecyclerView.Adapter<MovieListViewHolder>() {
            override fun onCreateViewHolder(
                parent: ViewGroup,
                viewType: Int
            ): MovieListViewHolder {
                return MovieListViewHolder(View.inflate(requireContext(),
                    R.layout.view_holder_movie_list_item, null),
                    channelType
                )
            }

            override fun getItemCount(): Int {
                return viewModel.getMovieList().size
            }

            override fun onBindViewHolder(holder: MovieListViewHolder, position: Int) {
                holder.bind(viewModel.getMovieList()[position], position)
            }
        }
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            @SuppressLint("NotifyDataSetChanged")
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                (recyclerView.layoutManager as LinearLayoutManager).run {
                    val lastVisiblePosition = findLastVisibleItemPosition()
                    if (lastVisiblePosition == itemCount - 1) {
                        mainScope.launch {
                            viewModel.loadMore()
                        }
                    }
                }
            }
        })
    }
}